<template>
    <a-modal 
        v-model:visible="modalVisible" 
        :title="getTitle" 
        :confirm-loading="loading" 
        @ok="handleSubmit" 
        @cancel="handleCancel"
        :ok-button-props="isViewing ? { style: { display: 'none' } } : {}"
        :cancel-text="isViewing ? '关闭' : '取消'"
        width="700px" 
        class="study-modal"
        :class="{ 'view-mode': isViewing }"
    >
        <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
            <!-- 学习内容 -->
            <a-form-item label="学习内容" name="content" :required="!isViewing">
                <a-textarea 
                    v-model:value="formState.content" 
                    placeholder="请输入学习内容，最多999个字符" 
                    :rows="4" 
                    show-count 
                    :maxlength="999"
                    :auto-size="{ minRows: 3, maxRows: 6 }"
                    :disabled="isViewing"
                    :readonly="isViewing"
                />
            </a-form-item>

            <a-row :gutter="16">
                <a-col :span="12">
                    <!-- 学习类型 -->
                    <a-form-item label="学习类型" name="type" :required="!isViewing">
                        <a-select 
                            v-model:value="formState.type" 
                            placeholder="请选择学习类型" 
                            size="large"
                            :disabled="isViewing"
                        >
                            <a-select-option value="前端">前端</a-select-option>
                            <a-select-option value="后端">后端</a-select-option>
                            <a-select-option value="数据库">数据库</a-select-option>
                            <a-select-option value="算法">算法</a-select-option>
                            <a-select-option value="运维">运维</a-select-option>
                            <a-select-option value="测试">测试</a-select-option>
                            <a-select-option value="架构">架构</a-select-option>
                            <a-select-option value="其他">其他</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <!-- 面试频率 -->
                    <a-form-item label="面试频率（次/周）" name="interviewFrequency">
                        <a-input-number 
                            v-model:value="formState.interviewFrequency" 
                            placeholder="请输入面试频率" 
                            :min="0" 
                            :max="100"
                            style="width: 100%"
                            size="large"
                            :disabled="isViewing"
                        />
                    </a-form-item>
                </a-col>
            </a-row>

            <!-- 应用场景 -->
            <a-form-item label="应用场景" name="applicationScenario" :required="!isViewing">
                <a-input 
                    v-model:value="formState.applicationScenario" 
                    placeholder="请输入应用场景，最多100个字符" 
                    show-count
                    :maxlength="100"
                    size="large"
                    :disabled="isViewing"
                    :readonly="isViewing"
                />
            </a-form-item>

            <!-- 备注信息 -->
            <a-form-item label="备注信息" name="remark">
                <a-textarea 
                    v-model:value="formState.remark" 
                    placeholder="请输入备注信息（可选）" 
                    :rows="3" 
                    show-count
                    :maxlength="200"
                    :disabled="isViewing"
                    :readonly="isViewing"
                />
            </a-form-item>
        </a-form>

        <!-- 查看模式下的操作按钮 -->
        <template v-if="isViewing" #footer>
            <a-button key="close" @click="handleCancel">关闭</a-button>
            <a-button 
                v-if="!isViewing" 
                key="submit" 
                type="primary" 
                :loading="loading" 
                @click="handleSubmit"
            >
                {{ isEditing ? '保存' : '新增' }}
            </a-button>
            <a-button 
                v-if="isViewing" 
                key="edit" 
                type="primary" 
                @click="handleEdit"
            >
                编辑
            </a-button>
        </template>
    </a-modal>
</template>

<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form'

interface StudyModalProps {
    visible: boolean
    isEditing: boolean
    isViewing?: boolean // 新增：查看模式
    editingData?: {
        id?: number
        content: string
        type: string
        applicationScenario: string
        interviewFrequency?: number
        remark?: string
    }
    loading?: boolean
}

interface StudyModalEmits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit', data: any): void
    (e: 'cancel'): void
    (e: 'edit'): void // 新增：编辑事件
}

const props = withDefaults(defineProps<StudyModalProps>(), {
    visible: false,
    isEditing: false,
    isViewing: false, // 默认不是查看模式
    loading: false
})

const emit = defineEmits<StudyModalEmits>()

// 表单引用
const formRef = ref()

// 表单状态
const formState = reactive({
    content: props.editingData?.content || '',
    type: props.editingData?.type || '',
    applicationScenario: props.editingData?.applicationScenario || '',
    interviewFrequency: props.editingData?.interviewFrequency || undefined,
    remark: props.editingData?.remark || ''
})

// 计算模态框标题
const getTitle = computed(() => {
    if (props.isViewing) {
        return '查看学习记录'
    } else if (props.isEditing) {
        return '编辑学习记录'
    } else {
        return '新增学习记录'
    }
})

// 表单验证规则（查看模式下不需要验证）
const rules = computed<Record<string, Rule[]>>(() => {
    if (props.isViewing) {
        // 查看模式下不需要验证规则
        return {}
    }
    
    return {
        content: [
            { required: true, message: '请输入学习内容', trigger: 'blur' },
            { min: 5, message: '学习内容至少5个字符', trigger: 'blur' },
            { max: 999, message: '学习内容最多999个字符', trigger: 'blur' }
        ],
        type: [
            { required: true, message: '请选择学习类型', trigger: 'change' }
        ],
        applicationScenario: [
            { required: true, message: '请输入应用场景', trigger: 'blur' },
            { max: 100, message: '应用场景最多100个字符', trigger: 'blur' }
        ],
        interviewFrequency: [
            { type: 'number', min: 0, max: 100, message: '面试频率应为0-100之间的数字', trigger: 'blur' }
        ]
    }
})

// 计算属性：同步 visible 状态
const modalVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
})

// 监听编辑数据变化，更新表单
watch(() => props.editingData, (newData) => {
    if (newData) {
        formState.content = newData.content || ''
        formState.type = newData.type || ''
        formState.applicationScenario = newData.applicationScenario || ''
        formState.interviewFrequency = newData.interviewFrequency || undefined
        formState.remark = newData.remark || ''
    } else {
        // 重置表单
        formState.content = ''
        formState.type = ''
        formState.applicationScenario = ''
        formState.interviewFrequency = undefined
        formState.remark = ''
    }
}, { immediate: true })

// 提交表单（查看模式下不提交）
const handleSubmit = async () => {
    if (props.isViewing) return // 查看模式下不处理提交
    
    try {
        await formRef.value?.validate()

        const submitData = {
            content: formState.content,
            type: formState.type,
            applicationScenario: formState.applicationScenario,
            interviewFrequency: formState.interviewFrequency ? Number(formState.interviewFrequency) : undefined,
            remark: formState.remark,
            id: props.isEditing ? props.editingData?.id : undefined
        }

        emit('submit', submitData)
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

// 取消操作/关闭
const handleCancel = () => {
    formRef.value?.resetFields()
    emit('cancel')
}

// 处理编辑操作（从查看模式切换到编辑模式）
const handleEdit = () => {
    emit('edit')
}

// 暴露方法供父组件调用
defineExpose({
    resetForm: () => formRef.value?.resetFields()
})
</script>

<style scoped>
.study-modal :deep(.ant-modal-content) {
    border-radius: 8px;
}

.study-modal :deep(.ant-modal-header) {
    background: linear-gradient(135deg, #1890ff 0%, #52c41a 100%);
    color: white;
}

.study-modal :deep(.ant-modal-title) {
    color: white;
    font-weight: 600;
}

.study-modal :deep(.ant-form-item-label) {
    font-weight: 500;
}

/* 查看模式下的特殊样式 */
.study-modal.view-mode :deep(.ant-input),
.study-modal.view-mode :deep(.ant-input-number),
.study-modal.view-mode :deep(.ant-select),
.study-modal.view-mode :deep(.ant-textarea) {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
    color: #666;
    cursor: not-allowed;
}

.study-modal.view-mode :deep(.ant-input):focus,
.study-modal.view-mode :deep(.ant-input-number):focus,
.study-modal.view-mode :deep(.ant-select):focus,
.study-modal.view-mode :deep(.ant-textarea):focus {
    box-shadow: none;
    border-color: #d9d9d9;
}

.study-modal.view-mode :deep(.ant-select-selector) {
    background-color: #f5f5f5;
}

.study-modal.view-mode :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 10px 16px;
    text-align: right;
}
</style>